package taglib;

import hibernate.IDao;

import java.io.IOException;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import utils.ReflectionUtils;
import config.Constant;



@SuppressWarnings("serial")
public class PropertyTag extends TagSupport{
	
	private String entityClass;
	private String valueProperty = "id";
	private String value;
	
	private String labelProperty;
	public int doStartTag()  {
		return (SKIP_BODY);
	}
	
	public int doEndTag()  {
		try {
			String resultStr = "";
			Class<?> clazz = Class.forName(entityClass);
			IDao dao = (IDao)Constant.AppContext.getBean("commonDAO");
			
			Object myValue = ReflectionUtils.convertStringToObject(value, ReflectionUtils.getDeclaredField(clazz,valueProperty).getType());
			Object object = dao.getByProperty(clazz, valueProperty, myValue);
			
			
			if(object!=null){
				Object labelValue = ReflectionUtils.getFieldValue(object, labelProperty);
				if(labelValue != null)
					resultStr = String.valueOf(labelValue);
			}
			JspWriter writer = pageContext.getOut();
			writer.write(resultStr);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		return (SKIP_BODY);
	}

	public String getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(String entityClass) {
		this.entityClass = entityClass;
	}
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getLabelProperty() {
		return labelProperty;
	}

	public void setLabelProperty(String labelProperty) {
		this.labelProperty = labelProperty;
	}

	public String getValueProperty() {
		return valueProperty;
	}

	public void setValueProperty(String valueProperty) {
		this.valueProperty = valueProperty;
	}
}
